# decoding=utf-8
from asyncio import ensure_future, get_event_loop
from aiomysql import create_pool, DictCursor
from Conf.setting import *
from common.read_Ini import Read_InI


class BASE_DB(object):
    def __init__(self, db_type: str = 'mysql', autocommit: bool = True, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.autocommit = autocommit
        if db_type.lower() == "mysql":
            self._loop = get_event_loop()
            self._database = create_pool
            self._ini = Read_InI(PROJECT_CONF_SETTING['project']).data['mysql']
            self._mysql = self.mysql
        elif db_type == "redis":
            pass

    @property
    def mysql(self):
        self._ini['autocommit'] = self.autocommit
        task = ensure_future(self._database(*self.args, **self._ini, **self.kwargs))
        self._loop.run_until_complete(task)
        return task.result()


class Mysql_Client(BASE_DB):

    @classmethod
    def setup(cls, con_type='mysql', *args, **kwargs):
        """前置"""
        return cls(
            con_type,
            *args,
            **kwargs
        )

    async def _select(self, sql: str, param: tuple = (), res_con: int = 1):
        async with self._mysql.acquire() as conn:
            async with conn.cursor(DictCursor) as cur:
                await cur.execute(sql.replace("?", "%s"), param)
                if cur.rowcount:
                    res = await cur.fetchmany(res_con)
                else:
                    res = await cur.fetchall()
            return res

    def select(self, *args, **kwargs):
        task = ensure_future(self._select(*args, **kwargs))
        self._loop.run_until_complete(task)
        return task.result()

    async def _execute(self, sql: str, param: tuple = ()):
        async with self._mysql.acquire() as conn:
            async with conn.cursor(DictCursor) as cur:
                await cur.execute(sql.replace("?", "%s"), param)
                if cur.rowcount > 0:
                    res = cur.rowcount
                else:
                    res = "execute  sql failed !!"
            return res

    def execute(self, *args, **kwargs):
        task = ensure_future(self._execute(*args, **kwargs))
        self._loop.run_until_complete(task)
        return task.result()


mysql_cl = Mysql_Client('mysql').setup()


